//
//  AppDelegate.swift
//  Weibo
//
//  Created by 潇 on 15/12/12.
//  Copyright © 2015年 潇. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        
        let account = UserAccount.loadAccount()
        print(account)
        
//        //版本 在defaultViewController前面调用会有缓存
//        let result = isNewVersion()
//        print(result)
        
        //如果不使用 storyboard,window 在这个地方没有被实例化,所以不会显示
        //需要手动创建 window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.makeKeyAndVisible()//显示
        
        setThemeColor()//设置导航条登录和注册的颜色
        
        
        //注册通知
        registerNotification()
        
        //写完上面的还是会报错,需要设置根控制器
         window?.rootViewController = defaultViewController()

        return true
    }
    
    //单例对象,只有程序运行的时候,建立 APPdelegate 单例对象,程序销毁的时候才会调用
    //注册通知
    private func registerNotification() {
        //注册切换根视图控制器的通知
        //object设置为空可以接收任何对象的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootVC:", name: WBSwitchRootVCNotification, object: nil)
    }
    
    //通知方法
    /**
    @objc 用到的地方总结: 
    只要是 OC 中 target-action 这只消息机制 seletor 类型都需要使用@ objc 来兼容
    1.按钮的点击事件
    2.通知的响应事件
    3.代理的可选协议方法
    
    */
    @objc private func switchRootVC(n: NSNotification) {
        print(n)
        //根据通知切换根视图控制器
        if n.object != nil {
            //有值 跳转到 Welcome
            window?.rootViewController = WelcomeViewController()
            return
        }
        //没有 首页
        window?.rootViewController = MainViewController()
    }
    
    
    //移除通知  移不移除没有区别,因为是单例   习惯性移除,保持完整性
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //根据用户是否登录判断显示具体页面
    private func defaultViewController() -> UIViewController {
        //根据用户是否登录
        if UserAccountViewModel().userLogin {
            //根据是够时新版本显示对于页面
//            if isNewVersion() {
//                //是新版本
//                return NewFeatureViewController()
//            }
//            return WelcomeViewController()
            return isNewVersion() ? NewFeatureViewController() : WelcomeViewController()
        }
        
        //用户没有登录
        
        return MainViewController()
    }
    //MARK: 判断是否是新版本
    private func isNewVersion() -> Bool {
    
        //1.获取当前应用的版本号
        let info = NSBundle.mainBundle().infoDictionary
//        print(info)
        let currentStr = info!["CFBundleShortVersionString"] as! String
        let currentNum = Double((currentStr))
        print(currentNum)
        //2.获取本地缓存的版本
        //用偏好设置出存储版本
        let userDefaults = NSUserDefaults.standardUserDefaults()
        let sandBoxKey = "sandBoxKey"
        let lastNum = userDefaults.doubleForKey(sandBoxKey)
        print(lastNum)
        //3.存储当前应用版本
        userDefaults.setDouble(currentNum!, forKey:sandBoxKey)
        userDefaults.synchronize()
        
        //4.比较新版本号和老版本号  判断是否为新
        return currentNum! > lastNum
    }
    
    
    private func setThemeColor() {
    
        //设置导航条登录和注册的颜色  需要提前设置
        UINavigationBar.appearance().tintColor = themeColor
        //设置tabbar 的背景色和文字颜色的第二种方法,可以一开始app 运行时就设置
        UITabBar.appearance().tintColor = themeColor
    }

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

